package com.hcl.security.filter;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.hcl.security.domain.CommonAuthentication;
import com.hcl.security.domain.LoginUser;
import com.hcl.security.domain.User;
import com.hcl.security.handle.AuthenticationEntryPointImpl;
import com.hcl.security.utils.JwtUtil;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 校验token
 */
public class ValidateTokenFilter extends OncePerRequestFilter {

	@Autowired
	private AuthenticationEntryPointImpl authenticationEntryPoint;

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if ("/login".equals(request.getRequestURI())) {
			filterChain.doFilter(request, response);
			return;
		}
		String token = request.getHeader("token");
		if (StringUtils.isEmpty(token)) {
			authenticationEntryPoint.commence(request, response,
					new BadCredentialsException("token不能为空"));
			return;
		}
		boolean tokenExpired = JwtUtil.isTokenExpired(token);
		if (tokenExpired) {
			authenticationEntryPoint.commence(request, response,
					new BadCredentialsException("token失效"));
			return;
		}
		User user = new User();
		user.setUsername("admin");
		user.setPassword("admin");
		LoginUser loginUser = new LoginUser(user, user.getUsername(),
				user.getPassword(), List.of("h"));
		Authentication authentication = new CommonAuthentication(loginUser,
				loginUser.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(authentication);

		filterChain.doFilter(request, response);
	}
}
